﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace cmdb.keede.com
{
    public static class ServiceCollectionExtentions
    {
        public static IServiceCollection RegisterServiceAssembly(this IServiceCollection sc, Type typeofService)
        {
            if (sc == null) throw new ArgumentNullException(nameof(sc));
            var types = Assembly.GetAssembly(typeofService).GetTypes().Where(w => w.Name.EndsWith("Service") && w.IsClass && !w.IsAbstract);

            foreach (var type in types)
            {
                var interfaceTypes = type.GetInterfaces();
                foreach (var interfaceType in interfaceTypes)
                {
                    sc.AddTransient(interfaceType, type);
                }
            }

            return sc;
        }

        public static IServiceCollection RegisterRepositoryAssembly(this IServiceCollection sc, Type typeofRepository)
        {
            if (sc == null) throw new ArgumentNullException(nameof(sc));
            var types = Assembly.GetAssembly(typeofRepository).GetTypes().Where(w => w.Name.EndsWith("Repository") && w.IsClass && !w.IsAbstract);

            foreach (var type in types)
            {
                var interfaceTypes = type.GetInterfaces();
                foreach (var interfaceType in interfaceTypes)
                {
                    sc.AddTransient(interfaceType, type);
                }
            }

            return sc;
        }
    }
}
